package com.intelligent.mts.client.core.view;

import com.google.common.collect.Lists;
import com.intelligent.mts.client.core.controller.MainController;
import com.intelligent.mts.client.event.StatusBarChangeEvent;
import com.intelligent.mts.client.utils.*;
import com.intelligent.mts.common.utils.ApplicationException;
import com.intelligent.mts.common.utils.ExceptionMessages;
import com.intelligent.mts.common.utils.StringUtils;
import com.intelligent.mts.core.dto.FinishGoodDto;
import com.intelligent.mts.core.utils.AppConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 * Created by Garen.Pang on 2016/8/19.
 */
@Component
public class BomPNPanel extends JPanel{

    @Autowired
    MainController mainController;

    String lastvalue[] = new String[9];

    public void setTextFieldValues(java.util.List<FinishGoodDto> list){

        if (list != null){
            for (FinishGoodDto fg:
                 list) {
                if (AppConst.FINISH_GOOD_KEY_FG.equals(fg.getKey())){
                    PNText.setText(fg.getPn());
//                    StatusText.setText(fg.getStatus());
                    if ("Disable".equals(fg.getStatus())){
                        setTextEnable();
                    }else {
                        setTextDisable();
                    }
//                    Disablebtn.setText(fg.getStatus());
                }else if(AppConst.FINISH_GOOD_KEY_HOU.equals(fg.getKey())){
                    HousingTextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_HS.equals(fg.getKey())){
                    HeatsinkTextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_MB_ASSY.equals(fg.getKey())){
                    MB_ASSYTextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_PCBA.equals(fg.getKey())){
                    PCBATextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_GW.equals(fg.getKey())){
                    GatewayTextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_DSP_P.equals(fg.getKey())){
                    DSP_PTextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_DSP_S.equals(fg.getKey())){
                    DSP_STextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_FCT.equals(fg.getKey())){
                    FCT_ProgramTextdis.setText(fg.getPn());
                }
                else if(AppConst.FINISH_GOOD_KEY_EOL.equals(fg.getKey())){
                    EOL_ProgramTextdis.setText(fg.getPn());
                }

            }
        }
    }

    @PostConstruct
    private void initComponents() {

        FinishGoodPanel = new JPanel();
        PNLabel = new JLabel();
        PNText = new JTextField();
        Disablebtn = new JButton("Disable");
        savebtn = new JButton("Save");

        HousingText = new JLabel();
        HousingTextdis = new JTextField();
        HeatsinkText = new JLabel();
        HeatsinkTextdis = new JTextField();
        MB_ASSYText = new JLabel();
        MB_ASSYTextdis = new JTextField();
        PCBAText = new JLabel();
        PCBATextdis = new JTextField();
        GatewayText = new JLabel();
        GatewayTextdis = new JTextField();
        DSP_PText = new JLabel();
        DSP_PTextdis = new JTextField();
        DSP_SText = new JLabel();
        DSP_STextdis = new JTextField();
        FCT_ProgramText = new JLabel();
        FCT_ProgramTextdis = new JTextField();
        EOL_ProgramText = new JLabel();
        EOL_ProgramTextdis = new JTextField();

        Disablebtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSetDisableActionPerformed(evt);
            }
        });

        savebtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                btnSaveActionPerformed(e);
            }
        });

        PNLabel.setText("FG PN:");

        HousingText.setText("Housing");
        HeatsinkText.setText("Heatsink");
        MB_ASSYText.setText("MB_ASSY");
        PCBAText.setText("PCBA");
        GatewayText.setText("Gateway");
        DSP_PText.setText("DSP_P");
        DSP_SText.setText("DSP_S");
        FCT_ProgramText.setText("FCT_program");
        EOL_ProgramText.setText("EOL_program");

        PNText.setEditable(false);

        this.setBorder((BorderFactory.createTitledBorder("FinishGood")));
        this.setLayout(new GridBagLayout());

//        PNLabel.setPreferredSize(new Dimension(100, 20));
        this.add(PNLabel,new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(0, 5, 0, 0));

        JPanel tempJpanel = new JPanel();
        tempJpanel.setLayout(new GridBagLayout());

        tempJpanel.add(PNText,new GBC(0, 0).setFill(GBC.BOTH).setWeight(80, 0).setInsets(1, 0, 0, 0));
        tempJpanel.add(Disablebtn, new GBC(1, 0).setFill(GBC.HORIZONTAL).setInsets(0, 5, 0, 0).setIpad(80,3));


        this.add(tempJpanel,new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(0, 0, 15, 5));

        JSeparator s1 = new JSeparator();
        s1.setPreferredSize(new Dimension(5, 5));
        s1.setOrientation(SwingConstants.HORIZONTAL );

        this.add(s1, new GBC(0,1).setFill(GBC.BOTH));

        JSeparator s2 = new JSeparator();
        s2.setPreferredSize(new Dimension(5, 5));
        s2.setOrientation(SwingConstants.HORIZONTAL );

        this.add(s2, new GBC(1,1).setFill(GBC.BOTH));

        JPanel detPanel = new JPanel();

//        detPanel.setLayout(new GridBagLayout());
        this.add(HousingText, new GBC(0,2).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(10, 5, 0, 0));
        this.add(HousingTextdis, new GBC(1, 2).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(10, 0, 0, 0));
        this.add(HeatsinkText, new GBC(0,3).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 0, 0));
        this.add(HeatsinkTextdis, new GBC(1, 3).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(2, 0, 0, 0));
        this.add(MB_ASSYText, new GBC(0,4).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 0, 0));
        this.add(MB_ASSYTextdis, new GBC(1, 4).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(2, 0, 0, 0));
        this.add(PCBAText, new GBC(0,5).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 0, 0));
        this.add(PCBATextdis, new GBC(1, 5).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(2, 0, 0, 0));
        this.add(GatewayText, new GBC(0,6).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 0, 0));
        this.add(GatewayTextdis, new GBC(1, 6).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(2, 0, 0, 0));
        this.add(DSP_PText, new GBC(0,7).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 0, 0));
        this.add(DSP_PTextdis, new GBC(1, 7).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(2, 0, 0, 0));
        this.add(DSP_SText, new GBC(0,8).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 0, 0));
        this.add(DSP_STextdis, new GBC(1, 8).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(2, 0, 0, 0));
        this.add(FCT_ProgramText, new GBC(0,9).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 5, 0));
        this.add(FCT_ProgramTextdis, new GBC(1, 9).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(2, 0, 5, 0));
        this.add(EOL_ProgramText, new GBC(0,10).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(0, 5, 5, 0));
        this.add(EOL_ProgramTextdis, new GBC(1, 10).setFill(GBC.HORIZONTAL).setWeight(90, 0).setInsets(0, 0, 5, 0));

//        detPanel.add(savebtn, new GBC(0, 8).setFill(GBC.HORIZONTAL).setWeight(10, 0).setInsets(4, 5, 5, 0));

//        this.add(detPanel , new GBC(0, 2).setFill(GBC.BOTH).setInsets(10, 5, 0, 0));

        this.add(new JPanel(), new GBC(0,11).setWeight(10, 0));
        JPanel btnpanel = new JPanel();
        btnpanel.setLayout(new GridBagLayout());
        btnpanel.add(new JPanel(), new GBC(0,0).setFill(GBC.HORIZONTAL).setWeight(100,0).setInsets(0, 5, 0, 0));
        btnpanel.add(savebtn, new GBC(1, 0).setFill(GBC.HORIZONTAL).setInsets(0, 5, 0, 0).setIpad(80,3));

        this.add(btnpanel, new GBC(1, 11).setFill(GBC.BOTH).setWeight(90, 0).setInsets(0, 5, 0, 10));
        this.add(new JLabel(), new GBC(1, 12).setFill(GBC.BOTH).setWeight(100, 100));

        setTextDisable();

    }

    private void btnSetDisableActionPerformed(ActionEvent evt) {
        try {
            if ("Enable".equals(Disablebtn.getText())){
                if (PNText.getText() == null || "".equals(PNText.getText())){
                    throw new ApplicationException(ExceptionMessages.EXCEPTION_FG_CANNOT_BE_EMPTY);
                }

                String result = disablevalidate();
                if (!"".equals(result) && result != null)
                {
                    JOptionPane.showMessageDialog(null, result+" already update,but you not save it. you should click save to save or click search to clear",
                            "error",JOptionPane.ERROR_MESSAGE);

                    throw new ApplicationException(ExceptionMessages.EXCEPTION_NOTSAVE_EDIT_PN);
                }

                String resultnullvalidae = disablevalidatenull();
                if (!"".equals(resultnullvalidae) && resultnullvalidae != null){

                    JOptionPane.showMessageDialog(null, resultnullvalidae+" is(are) null. you should fill it first.",
                            "error",JOptionPane.ERROR_MESSAGE);
                    throw new ApplicationException( ExceptionMessages.EXCEPTION_DISABLE_NULL_PN);
                }

                if (!mainController.validateGwAndPcba(PNText.getText(), GatewayTextdis.getText(), PCBATextdis.getText())){
                    //throw message
                    JOptionPane.showMessageDialog(null, "GW PCBA already exits.",
                            "error",JOptionPane.ERROR_MESSAGE);
                    throw new ApplicationException(ExceptionMessages.EXCEPTION_GAT_PCBA_ALREADY_EXITS);
                }

                mainController.updateFinishGoodStatus(Disablebtn.getText(),ApplicationBeanUtils.getBean(BomSearchPanel.class).getCustomer().getSelectedItem().toString(),PNText.getText());
//                setTextDisable();
                setTextDisable();
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ActionMessages.UPDATE_FGPN_STATUS)));
            }else {

                if (PNText.getText() == null|| "".equals(PNText.getText())){
                    throw new ApplicationException(ExceptionMessages.EXCEPTION_FG_CANNOT_BE_EMPTY);
                }

                mainController.updateFinishGoodStatus( Disablebtn.getText(),ApplicationBeanUtils.getBean(BomSearchPanel.class).getCustomer().getSelectedItem().toString(),PNText.getText());
//                setTextEnable()
                setTextEnable();;
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ActionMessages.UPDATE_FGPN_STATUS)));
            }

        } catch (ApplicationException ex) {
            if(ResourceBundleUtils.getString(ex.getMessage()) == null || "".equals(ResourceBundleUtils.getString(ex.getMessage()))){
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_SYSTERM_ERROR), StatusBarChangeEvent.MSG_LEVEL_ERROR));
            }else
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ex.getMessage()), StatusBarChangeEvent.MSG_LEVEL_ERROR));
        }
    }

    public void initlastvale(){
        lastvalue[0]  = HousingTextdis.getText();
        lastvalue[1]  = HeatsinkTextdis.getText();
        lastvalue[2]  = MB_ASSYTextdis.getText();
        lastvalue[3]  = PCBATextdis.getText();
        lastvalue[4]  = GatewayTextdis.getText();
        lastvalue[5]  = DSP_PTextdis.getText();
        lastvalue[6]  = DSP_STextdis.getText();
        lastvalue[7]  = FCT_ProgramTextdis.getText();
        lastvalue[8]  = EOL_ProgramTextdis.getText();

    }

    private String disablevalidatenull(){

        StringBuffer sb = new StringBuffer();
        if (lastvalue[0]== null || "".equals(lastvalue[0]) || StringUtils.isBlank(lastvalue[0])){
            sb.append("Housing \n");
        }
        if (lastvalue[1]== null || "".equals(lastvalue[1]) || StringUtils.isBlank(lastvalue[1])){
            sb.append("Heatsink \n");
        }
        if (lastvalue[2]== null || "".equals(lastvalue[2]) || StringUtils.isBlank(lastvalue[2])){
            sb.append("MB_ASSY \n");
        }
        if (lastvalue[3]== null || "".equals(lastvalue[3]) || StringUtils.isBlank(lastvalue[3])){
            sb.append("PCBA \n");
        }
        if (lastvalue[4]== null || "".equals(lastvalue[4]) || StringUtils.isBlank(lastvalue[4])){
            sb.append("Gateway \n");
        }
        if (lastvalue[5]== null || "".equals(lastvalue[5]) || StringUtils.isBlank(lastvalue[5])){
            sb.append("DSP_P \n");
        }
        if (lastvalue[6]== null || "".equals(lastvalue[6]) || StringUtils.isBlank(lastvalue[6])){
            sb.append("DSP_S \n");
        }
        if (lastvalue[7]== null || "".equals(lastvalue[7]) || StringUtils.isBlank(lastvalue[7])){
            sb.append("FCT_Program \n");
        }
        if (lastvalue[8]== null || "".equals(lastvalue[8]) || StringUtils.isBlank(lastvalue[8])){
            sb.append("EOL_Program \n");
        }
        return sb.toString();
    }

    private String disablevalidate(){

        StringBuffer sb = new StringBuffer();
        if (lastvalue[0]!= null && !lastvalue[0].equals(HousingTextdis.getText())){
            sb.append("Housing \n");
        }
        if (lastvalue[1]!= null && !lastvalue[1].equals(HeatsinkTextdis.getText())){
            sb.append("Heatsink \n");
        }
        if (lastvalue[2]!= null && !lastvalue[2].equals(MB_ASSYTextdis.getText())){
            sb.append("MB_ASSY \n");
        }
        if (lastvalue[3]!= null && !lastvalue[3].equals(PCBATextdis.getText())){
            sb.append("PCBA \n");
        }
        if (lastvalue[4]!= null && !lastvalue[4].equals(GatewayTextdis.getText())){
            sb.append("Gateway \n");
        }
        if (lastvalue[5]!= null && !lastvalue[5].equals(DSP_PTextdis.getText())){
            sb.append("DSP_P \n");
        }
        if (lastvalue[6]!= null && !lastvalue[6].equals(DSP_STextdis.getText())){
            sb.append("DSP_S \n");
        }
        if (lastvalue[7]!= null && !lastvalue[7].equals(FCT_ProgramTextdis.getText())){
            sb.append("FCT_Program \n");
        }
        if (lastvalue[8]!= null && !lastvalue[8].equals(EOL_ProgramTextdis.getText())){
            sb.append("EOL_Program \n");
        }

        return sb.toString();
    }

    private void btnSaveActionPerformed(ActionEvent evt) {
        try {

            if ("Enable".equals(Disablebtn.getText())){
//                mainController.updateFinishGoodStatus(PNText.getText(), Disablebtn.getText());
                Map<String, String> map = installFG();
                List<String> pns = Lists.newArrayList();
                pns.addAll(map.values());
                if (!mainController.validatePnIsInFgPn(pns)){
                    //throw message
                    JOptionPane.showMessageDialog(null, "FG PN already exits.",
                            "error",JOptionPane.ERROR_MESSAGE);
                    throw new ApplicationException(ExceptionMessages.EXCEPTION_GAT_PCBA_ALREADY_EXITS);
                }

                // validate GW PCBA,save not validate now
//                if (!mainController.validateGwAndPcba(PNText.getText(), GatewayTextdis.getText(), PCBATextdis.getText())){
//                    //throw message
//                    JOptionPane.showMessageDialog(null, "GW PCBA already exits.",
//                            "error",JOptionPane.ERROR_MESSAGE);
//                    throw new ApplicationException(ExceptionMessages.EXCEPTION_GAT_PCBA_ALREADY_EXITS);
//                }


                String Customer = ApplicationBeanUtils.getBean(BomSearchPanel.class).getCustomer().getSelectedItem().toString();
                String fgpn = ApplicationBeanUtils.getBean(BomSearchPanel.class).getFGPN().getSelectedItem().toString();
                mainController.updateFinishGood(map, Customer, fgpn);

                ApplicationBeanUtils.getBean(BomSearchPanel.class).btnsearchclick();
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ActionMessages.UPDATE_FGPN_DONE)));

            }else{
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ActionMessages.UPDATE_FGPN_DISABLE), StatusBarChangeEvent.MSG_LEVEL_ERROR));
            }
//            setTextDisable();
        } catch (ApplicationException ex) {
            if(ResourceBundleUtils.getString(ex.getMessage()) == null || "".equals(ResourceBundleUtils.getString(ex.getMessage()))){
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_SYSTERM_ERROR), StatusBarChangeEvent.MSG_LEVEL_ERROR));
            }else
                EventBusUtils.post(new StatusBarChangeEvent(ResourceBundleUtils.getString(ex.getMessage()), StatusBarChangeEvent.MSG_LEVEL_ERROR));
        }
    }

    private Map<String, String>  installFG(){

        Map finishGood = new HashMap<String, String>();

        finishGood.put(AppConst.FINISH_GOOD_KEY_HOU,HousingTextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_HS, HeatsinkTextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_MB_ASSY, MB_ASSYTextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_PCBA, PCBATextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_GW, GatewayTextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_DSP_P, DSP_PTextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_DSP_S, DSP_STextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_FCT, FCT_ProgramTextdis.getText());
        finishGood.put(AppConst.FINISH_GOOD_KEY_EOL, EOL_ProgramTextdis.getText());

        return finishGood;
    }

    private void setTextDisable(){
        HousingTextdis.setEditable(false);
        HeatsinkTextdis.setEditable(false);
        MB_ASSYTextdis.setEditable(false);
        PCBATextdis.setEditable(false);
        GatewayTextdis.setEditable(false);
        DSP_PTextdis.setEditable(false);
        DSP_STextdis.setEditable(false);
        FCT_ProgramTextdis.setEditable(false);
        EOL_ProgramTextdis.setEditable(false);
//        StatusText.setText("Disable");
        Disablebtn.setText("Disable");
    }

    private void setTextEnable(){
        HousingTextdis.setEditable(true);
        HeatsinkTextdis.setEditable(true);
        MB_ASSYTextdis.setEditable(true);
        PCBATextdis.setEditable(true);
        GatewayTextdis.setEditable(true);
        DSP_PTextdis.setEditable(true);
        DSP_STextdis.setEditable(true);
        FCT_ProgramTextdis.setEditable(true);
        EOL_ProgramTextdis.setEditable(true);
//        StatusText.setText("Disable");
        Disablebtn.setText("Enable");
    }

    public void deleteAllData(){
        PNText.setText("");
        HousingTextdis.setText("");
        HeatsinkTextdis.setText("");
        MB_ASSYTextdis.setText("");
        PCBATextdis.setText("");
        GatewayTextdis.setText("");
        DSP_PTextdis.setText("");
        DSP_STextdis.setText("");
        FCT_ProgramTextdis.setText("");
        EOL_ProgramTextdis.setText("");
        Disablebtn.setText("Disable");
    }

    private JPanel FinishGoodPanel;
    private JLabel PNLabel;
    private JTextField PNText;
//    private JLabel StatusLabel;
//    private JTextField StatusText;
    private JButton Disablebtn;
    private JButton savebtn;

//    private JLabel DiscriptionText;
//    private JLabel PNTexttab;
//    private JTextField FGtext;
//    private JTextField FGtextdis;
    private JLabel HousingText;
    private JTextField HousingTextdis;
    private JLabel HeatsinkText;
    private JTextField HeatsinkTextdis;
    private JLabel MB_ASSYText;
    private JTextField MB_ASSYTextdis;
    private JLabel PCBAText;
    private JTextField PCBATextdis;
    private JLabel GatewayText;
    private JTextField GatewayTextdis;
    private JLabel DSP_PText;
    private JTextField DSP_PTextdis;
    private JLabel DSP_SText;
    private JTextField DSP_STextdis;
    private JLabel FCT_ProgramText;
    private JTextField FCT_ProgramTextdis;
    private JLabel EOL_ProgramText;
    private JTextField EOL_ProgramTextdis;

}

